package com.smartResponse;

import android.widget.*;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.database.Cursor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;


//We need to develop a way to make sure that the same name can not be entered twice.



public class EditLocation extends Activity {
    EventDB db = new EventDB(this);
    static double lng;
    static double lat;
    static String address_extra;
    static double myRadius;
    static boolean changed;
    String bundle_l_name;
    long id;
	public static void setLocationVars(double latitude, double longitude, String address, double radius, boolean change){
		lng = longitude;
		lat = latitude;
		address_extra = address;
		myRadius = radius;
		changed = change;
	 }
	
		@Override
		public void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.editlocationlayout);
		    Spinner spinner = (Spinner) findViewById(R.id.spinner_audio_settings);
		    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.audioSettings, android.R.layout.simple_spinner_item);
		    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    spinner.setAdapter(adapter);
		    Bundle extras = getIntent().getExtras(); 
		    if(extras !=null)
		    {
		    bundle_l_name = extras.getString("location");
		    }
		    else{
		    	bundle_l_name = "";
		    }
		    EditText name = (EditText) findViewById(R.id.l_name);
		    EditText radius= (EditText) findViewById(R.id.l_radius);
		    EditText address = (EditText) findViewById(R.id.l_address);
		    EditText longitude = (EditText) findViewById(R.id.l_longitude);
		    EditText latitude = (EditText) findViewById(R.id.l_latitude);
		    CheckBox status = (CheckBox) findViewById(R.id.l_status);
            Spinner audio_spinner = (Spinner)findViewById(R.id.spinner_audio_settings);

		    db.open();
	        Cursor c = db.getAllLocations();
			//finds the record in the database from a location name
	        while (c.moveToNext())
	        {
	            String results = c.getString(1); 

				if(results.equals(bundle_l_name))
				{
				id = c.getLong(0);
				}
	        }
	        //end lookup
	         Cursor c2 = db.getAllLocations();
	        while (c2.moveToNext())
	        {
	            long results = c2.getLong(0); 

				if(results == id)
				{
					name.setText(c2.getString(1));
			        address.setText(c2.getString(2));
			        longitude.setText(c2.getString(3));
			        latitude.setText(c2.getString(4));
					radius.setText(c2.getString(5));	
					//ADD IF STATEMENTS TO SET SPINNER TO CORRECT DB VALUE
					if (c2.getString(6).equals("Ringer")){
			        audio_spinner.setSelection(0);
					}
					if (c2.getString(6).equals("Vibrate")){
				        audio_spinner.setSelection(1);
					}
					if (c2.getString(6).equals("Silent")){
				        audio_spinner.setSelection(2);
					}
					String status2 = c2.getString(7);
					if (status2.equals("Enabled")){
						Log.d("Working", "Enabled");
						status.setChecked(true);  
					}
				}
	        }
	        //end lookup
	        db.close();
		    
	        //This code changes address after a new one is added
	        if (changed == true){
		        address.setText(address_extra);
	        	longitude.setText(String.valueOf(lng));
	        	latitude.setText(String.valueOf(lat));
	        	radius.setText(String.valueOf(myRadius));
	        }
		    
		    on_showMap_Button_Click();
	        on_OK_Button_Click();
	        on_Cancel_Button_Click();
}
		private void on_showMap_Button_Click() {
			Button Button = (Button) findViewById(R.id.show_map);
			
			Button.setOnClickListener(new OnClickListener(){
				public void onClick(View v){
					
					Intent in = new Intent(EditLocation.this, LocationMap.class);
					in.putExtra("Activity", "EditLocation");
					in.putExtra("location", getIntent().getExtras().getString("location"));
					startActivityForResult(in,1);
	                }	
			});
		}

		public void on_OK_Button_Click() {
			
			Button Button = (Button) findViewById(R.id.l_ok);
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {
					//The code below stores the text in the box to a string
				    EditText name = (EditText) findViewById(R.id.l_name);
				    EditText radius= (EditText) findViewById(R.id.l_radius);
				    EditText address = (EditText) findViewById(R.id.l_address);
				    EditText longitude = (EditText) findViewById(R.id.l_longitude);
				    EditText latitude = (EditText) findViewById(R.id.l_latitude);
				    CheckBox status = (CheckBox) findViewById(R.id.l_status);
				    
		        	String et_name = name.getText().toString();
					String et_radius = radius.getText().toString();
					String et_address = address.getText().toString();
		        	String et_longitude = longitude.getText().toString();
		        	String et_latitude = latitude.getText().toString();

	        		db.open();
			        Cursor c = db.getAllLocations();
			            Spinner mySpinner = (Spinner)findViewById(R.id.spinner_audio_settings);
			            String audio = mySpinner.getSelectedItem().toString();
						//finds the record in the database from a location name
			            String db_name = "";
			            String db_address = "";
			            String db_lng = "";
			            String db_lat = "";
			            String db_radius = "";
			            String db_audio = "";
			            String db_status = "";
				        while (c.moveToNext())
				        {
				            long results = c.getLong(0); 

							if(results == id)
							{
							db_name=c.getString(1);
							db_address=c.getString(2);
							db_lng=c.getString(3);
							db_lat=c.getString(4);
							db_radius=c.getString(5);
							db_audio=c.getString(6);
							db_status = c.getString(7);
							}
				        }
				        //end lookup
				        db.close();
				        
				        //The if statements below check for change in location record data
				       	if (db_name.equals(et_name)){
				        	}
				        		else{
					        		et_name.equals(db_name);
				        		}
				        	if (db_radius.equals(et_radius)){
				        	}
				        		else{
				        		et_radius.equals(db_radius);
				        	}
				        	if (db_address.equals(et_address)){
				        	}
				        		else{
				        		et_address.equals(db_address);
				        	}
				        	if (db_lng.equals(et_longitude)){
				        	}
				        		else{
				        		et_longitude.equals(db_lng);
				        	}
				        	if (db_lat.equals(et_latitude)){
				        	}
				        		else{
				        		et_latitude.equals(db_lat);
				        	}
				        	if (db_audio.equals(audio)){
				        	}
				        		else{
				        		audio.equals(db_audio);
				        	}
				        	if (status.isChecked() == true){
				        		db_status = "Enabled";
				        	}
				        	if (status.isChecked() == false){
				        		db_status = "Disabled";
				        	}
				        //The code below is error handeling to make sure correct data is entered into the fields
						    boolean name_is_valid = true;
						    boolean valid_radius = true;
						    boolean valid_location = true;
						    db.open();
					        Cursor c1 = db.getAllLocations();
					        while (c1.moveToNext())
					        {
					            String results = c1.getString(1);
					            if (results.equals(et_name))
					            { 	
					            	 name_is_valid=false;
					            	 }
					        }
					        db.close();
					        if (et_name.equals(bundle_l_name)){
					        	name_is_valid=true;
					        }
					        if  (et_name == null || et_name.isEmpty()){
					        	name_is_valid = false;
					        }
					        if (name_is_valid == true){	
					            Spinner mySpinner1 = (Spinner)findViewById(R.id.spinner_audio_settings);
					            String audio1 = mySpinner1.getSelectedItem().toString();	
						        //checks if frequency is valid
					        	if (et_radius == null || et_radius.isEmpty()) {
					        		valid_radius = false;
					        		} else {
					        		   try {
					        		     @SuppressWarnings("unused")
										double num = Double.parseDouble(et_radius);
					        		   }
					        		   catch (NumberFormatException e) {
					        			   valid_radius = false;
					        		   }
					        		}
					        	if (valid_radius == true){
					        		//Checks if the location has been changed
						        	if (et_longitude.isEmpty() || et_latitude.isEmpty()) {
						        		valid_location = false;
						        		} else {
						        		   try {
						        		     double lng = Double.parseDouble(et_longitude);
						        		    double lat = Double.parseDouble(et_latitude);
						        		    if (lng >= -180 || lng <= 180){
						        		    	valid_location = true;
						        		    }
						        		    if (lat >= -90 || lat <= 90){
						        		    	valid_location = true;
						        		    }
						        		   }
						        		   catch (NumberFormatException e) {
						        			   valid_location = false;
						        		   }
						        		}
						        	if (valid_location == true){
							            updatelocation(id, et_name, et_address,et_longitude, et_latitude, et_radius, audio1, db_status);
							        	ViewLocation.change_name(et_name); 
								        Intent in = new Intent();
								        setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
								        address_extra = null;
								        lng = 0.0;
								        lat = 0.0;
								        finish();
						        	}
						        	if (valid_location == false){
							        	Context context = getApplicationContext();
							        	CharSequence text = "Please select 'Show Map' to enter a new location or edit the location to appropriate values.";
							        	int duration = Toast.LENGTH_LONG;
							        	Toast toast = Toast.makeText(context, text, duration);
							        	toast.show();	
						        	}

					        	}
					        	if (valid_radius == false){
						        	Context context = getApplicationContext();
						        	CharSequence text = "Please enter a radius, in feet, that you would like around your location (numbers only).";
						        	int duration = Toast.LENGTH_LONG;
						        	Toast toast = Toast.makeText(context, text, duration);
						        	toast.show();				        	
						        }
					        }
					        if (name_is_valid == false)
					        {	
					        	Context context = getApplicationContext();
					        	CharSequence text = "That name is already in use or is invalid, please enter a different name";
					        	int duration = Toast.LENGTH_LONG;

					        	Toast toast = Toast.makeText(context, text, duration);
					        	toast.show();
					        }
			        }
				

			} );
	}
		public void on_Cancel_Button_Click() {
			 
			Button Button = (Button) findViewById(R.id.l_cancel);
	 
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {
			        Intent in = new Intent();
			        setResult(RESULT_CANCELED,in);//Here I am Setting the Requestcode to 0, This will not update the activity
			        address_extra = null;
			        lng = 0.0;
			        lat = 0.0;
			        finish();
				}

			} );
	}

	    public void updatelocation(long id, String name, String address, String longitude, 
				String latitude, String radius, String audio, String status)
	    {
	    	EventDB db = new EventDB(this);
	        db.open();        
	        db.updateLocation(
	        		id,
	        		name,
	        		address,
	        		longitude,
	        		latitude,
	        		radius,
	        		audio,
	        		status);        
	        db.close();
	    	
	    } 
		//The code in the function below checks to see if a new location was added and if so it refreshes the page
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	        
	        if(resultCode==1){
			    final EditText address = (EditText) findViewById(R.id.l_address);
			    final EditText longitude = (EditText) findViewById(R.id.l_longitude);
			    final EditText latitude = (EditText) findViewById(R.id.l_latitude);
	        	address.setText(address_extra);
	        	longitude.setText(String.valueOf(lng));
	        	latitude.setText(String.valueOf(lat));
			    Toast.makeText(EditLocation.this, "New Address is :" + address_extra +"\n" +"New Latitude is: " + lat + "\n" + "New Longitude is: " + lng, Toast.LENGTH_SHORT).show();
			    Intent refresh = new Intent(EditLocation.this, EditLocation.class);
			    refresh.putExtra("location", getIntent().getExtras().getString("location"));
	            this.finish();
	            startActivity(refresh);

	        }
	        if(resultCode==RESULT_CANCELED){
	            Intent refresh = new Intent(EditLocation.this, EditLocation.class);
	            startActivity(refresh);
	            this.finish();
	        }
	        
	    }
		//This code controls what happens when the back key is pressed
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)  {
		    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
		    	on_Cancel_Button_Click();
		    }

		    return super.onKeyDown(keyCode, event);
		}
		//Menu Layout
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
			menu.add(0,1,0,"Home").setIcon(R.drawable.home);
	        menu.add(0,2,0,"OK").setIcon(R.drawable.add_icon);
	        menu.add(0,3,0,"Cancel").setIcon(R.drawable.cancel);
		    return true;
		}
	    @Override
	     public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case 1:
			  Intent home_intent_menu = new Intent(EditLocation.this, MainActivity.class);
		        address_extra = null;
		        lng = 0.0;
		        lat = 0.0;
			  startActivity(home_intent_menu);
			  return true;
	        case 2:
	        	on_OK_Button_Click();
	        	return true;
	     case 3:
	    	 	on_Cancel_Button_Click();
	            return true;
	          }
			return false;
	    }
}